<template>
    <div class="flexStar">
      <draggable :list="value" class="mul-draggable" :options="{disabled}" filter=".unmover">
        <div v-for="(item, index) in value" :key="item.fileId" class="marright10 imgBox">
          <img
            class="pic imgList"
            :src="item.fileUrl"
            v-if="!isVideoFile(item.fileUrl)"
            :style="{
              width: width + 'px',
              height: (height ? height : width) + 'px',
              lineHeight: (height ? height : width) + 'px',
            }"
          />
          <video
            :src="item.fileUrl"
            v-if="isVideoFile(item.fileUrl)"
            :style="{
              width: width + 'px',
              height: (height ? height : width) + 'px',
              lineHeight: (height ? height : width) + 'px',
            }"
          ></video>
            <span class="upload-wrapper-del delete" @click.stop="handleRemove(index)">
                <i class="el-icon-close"></i>
            </span>
        </div>
        <el-upload
            v-if="!limitNum || value.length < limitNum"
            v-loading="loading"
            action="#"
            :http-request="httpRequest"
            class="pic-uploader-component unmover"
            :style="{ width: width + 'px', height: (height ? height : width) + 'px' }"
            v-show="value.length <= 20"
            :show-file-list="false"
            :multiple="true"
            :before-upload="beforeAvatarUpload"
        >
            <i
            class="el-icon-plus pic-uploader-icon"
            :style="{
                width: width + 'px',
                height: (height ? height : width) + 'px',
                lineHeight: (height ? height : width) + 'px',
            }"
            ></i>
        </el-upload>
      </draggable>
    </div>
</template>
  
  <script>
  // :action="resourcesUrl + '/inf-bridge-service/back/storage/file/upload'" :headers="{Authorization: token}"
  import draggable from 'vuedraggable'
  import { array } from "jszip/lib/support";
  import _axios from "@/api/axios";
  export default {
    components: {
        draggable
    },
    data() {
      return {
        resourcesUrl: "",
        token: "",
        loading: false,
      };
    },
    props: {
      value: {
        default: "",
        type: array,
      },
      // 文件大小
      limitSize: {
        default: 10,
        type: [Number, String],
      },
      // 是否校验比例
      sizeVisible: {
        default: false,
        type: Boolean,
      },
      // 占位大小
      width: {
        default: 148,
        type: Number,
      },
      height: {
        default: 148,
        type: Number,
      },
      // 比例
      proportion: {
        default: 1,
        type: [Number, String],
      },
      limitNum: {
        type: Number,
        default: 0,
      },
      // 是否支持视频上传
      video: {
        type: Number,
        default: 0,
      },
      // 是否禁止拖动 默认可拖动
      disabled: {
        type: Boolean,
        default: () => true
      }
    },
    created() {
      this.resourcesUrl = process.env.VUE_APP_BASE_API;
      this.token = localStorage.getItem("token");
    },
    methods: {
      httpRequest(row) {
        let currentIsVideo = this.isVideoFile(row.file.name);
        let formData = new FormData();
        let videoLoadUrl =
          process.env.NODE_ENV == "development"
            ? "http://121.37.164.213:9043/back/storage/video/upload"
            : "https://bsgmini.cqbsyou.com/uploadMax";
        formData.append("file", row.file);
        _axios({
          headers: { Authorization: this.token },
          method: "post",
          url:
            currentIsVideo && this.video
              ? videoLoadUrl
              : "/inf-bridge-service/back/storage/file/upload",
          data: formData,
        })
          .then((res) => {
            console.log(res, "res");
            let arr = [...this.value, res];
            if (this.limitNum > 0) {
              arr.splice(this.limitNum, arr.length - this.limitNum);
            }
            this.$emit("input", arr);
          })
          .catch((error) => {
            this.$message.error("上传图片失败");
          });
      },
      handleUploadProgress(e, file, fileList) {
        this.loading = true;
      },
      handleUploadError(err, file, fileList) {
        this.loading = false;
      },
      // 限制图片上传大小
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < parseInt(this.limitSize);
        if (!isLt2M) {
          this.$message.error(`上传图片大小不能超过 ${this.limitSize}MB!`);
          return false;
        }
        if (this.sizeVisible) {
          const isSize = new Promise(function (resolve, reject) {
            let _URL = window.URL || window.webkitURL;
            let image = new Image();
            image.onload = function () {
              let valid = image.width / image.height === (this.proportion || 1);
              valid ? resolve() : reject();
            };
            image.src = _URL.createObjectURL(file);
          }).then(
            () => {
              return file;
            },
            () => {
              this.$message.error("上传头像图片尺寸不符合");
              return Promise.reject(false);
            }
          );
          let typeArr = file.name.split(".");
          const fileType = typeArr[typeArr.length - 1].toLowerCase();
          const fileTypeStr = "jpg,png,jpeg";
          if (fileTypeStr.indexOf(fileType) < 0 && !this.video) {
            this.$message.warning("图片格式只能为jpg或png");
            return false;
          }
          return isSize;
        } else {
          let typeArr = file.name.split(".");
          const fileType = typeArr[typeArr.length - 1].toLowerCase();
          const fileTypeStr = "jpg,png,jpeg";
          if (fileTypeStr.indexOf(fileType) < 0 && !this.video) {
            this.$message.warning("图片格式只能为jpg或png");
            return false;
          }
        }
        return isLt2M;
      },
      // 移除
      handleRemove(index) {
        this.$emit("delteImage", index);
      },
      // 获取文件格式
      getTypeByFilePath(path) {
        if (path != undefined) {
          return path.substring(path.lastIndexOf("."), path.length);
        }
      },
      // 是否是视频
      isVideoFile(path) {
        let videos = [".mp4", ".ogg", ".webm"];
        return videos.includes(this.getTypeByFilePath(path));
      },
    },
  };
  </script>
  
  <style lang="scss" scoped>
  .flexStar {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  .marright10 {
    margin-right: 10px;
  }
  .imgList {
    border-radius: 3px;
    cursor: pointer;
  }
  .imgBox {
    position: relative;
    margin-bottom: 8px;
    &:hover {
      .delete {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .delete {
      cursor: pointer;
      display: none;
    }
  }
  </style>
  <style lang="scss" scoped>
  .mul-draggable{
    display: inline-flex;
    flex-wrap: wrap;
  }
  .pic-uploader-component .el-upload {
    border: 1px solid #DCDFE6;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  
    .pic-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 104px;
      height: 104px;
      line-height: 104px;
      text-align: center;
    }
  
    .pic {
      width: 104px;
      height: 104px;
      display: block;
    }
  }
  
  .pic-uploader-component {
    width: 104px;
    height: 104px;
    margin-bottom: 8px;
  }
  
  .pic-uploader-component .el-upload:hover {
    border-color: #409eff;
  }
  
  .upload-wrapper-del {
    position: absolute;
    right: 10px;
    top: 10px;
    background: rgba($color: #000000, $alpha: 0.5);
    border-radius: 50%;
  
    i {
      color: #fff;
      font-size: 18px;
    }
  }
  </style>
  